﻿using AutoMapper;

using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

using System;
using System.Collections.Generic;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


using ZFB.Common;
using ZFB.DTO;
using ZFB.IServices;
using ZFB.Models;
using ZFB.Repository.AdminUser;

namespace ZFB.Services
{
    public class AdminUserServices : IAdminUserServices
    {
        private readonly IAdminUserRepository AdminUserRepository;
        private readonly IAdminLogServices AdminLogServices;
        private readonly IMapper mapper;
        public AdminUserServices(IAdminUserRepository adminUserRepository, IAdminLogServices adminLogServices, IMapper mapper)
        {
            AdminUserRepository = adminUserRepository;
            AdminLogServices = adminLogServices;
            this.mapper = mapper;
        }

        public async Task<ApiResult> AddNewUserAsync(string name, string phoneNum, string password, string email, long? cityid)
        {
            if (await AdminUserRepository.IsExistAsync(e => e.PhoneNum == phoneNum)) return new ApiResult("账号已存在");
            var salt = CommonHelper.CreateVerifyCode(8);
            var psw = CommonHelper.CalcMD5(password + salt);
            var res = await AdminUserRepository.AddAsync(new T_AdminUsers
            {
                Name = name,
                PhoneNum = phoneNum,
                PasswordHash = psw,
                Email = email,
                CityId = cityid,
                PasswordSalt = salt
            });
            return res <= 0 ? new ApiResult("注册失败！") : new ApiResult();
        }

        public async Task<ApiResult> CheckLoginAsync(string phoneNum, string password)
        {
            var user = await AdminUserRepository.GetModelAsync(e => e.PhoneNum == phoneNum);
            if (user == null) return new ApiResult("账号不存在");
            var psd = CommonHelper.CalcMD5(password + user.PasswordSalt);
            if (user.PasswordHash == psd)
            {
                //JWT
                string msg = $"账号为{user.PhoneNum}的用户于{DateTime.Now}登录";
                await AdminLogServices.AddNewAsync(user.Id, msg);
                return new ApiResult("登录成功");
            }
            return new ApiResult("账号或密码错误");
        }

        public  async Task<ApiResult> GetAllAsync()
        {
            var data = await AdminUserRepository.GetListAsync();
            
            if (data.IsNullOrEmpty())
            {
                return new ApiResult("获取失败!");
            }
            else
            {
               var dto= mapper.Map<List<AdminUserDTO>>(data);
               return new ApiResult(dto);
            }


        }

        public async Task<ApiResult> GetAllByCityIdAsync(long? cityid)
        {

            var data = await AdminUserRepository.GetListAsync(e=>e.CityId==cityid);

            if (data.IsNullOrEmpty())
            {
                return new ApiResult("获取失败!");
            }
            else
            {
                var dto = mapper.Map<List<AdminUserDTO>>(data);
                return new ApiResult(dto);
            }
        }

        public async Task<ApiResult> GetByIdAsync(long id)
        {
            var data = await AdminUserRepository.GetListAsync(e => e.Id == id);

            if (data.IsNullOrEmpty())
            {
                return new ApiResult("用户不存在!");
            }
            else
            {
                var dto = mapper.Map<List<AdminUserDTO>>(data);
                return new ApiResult(dto);
            }
        }

        public async Task<ApiResult> GetByPhoneAsync(string phoneNum)
        {
            var data = await AdminUserRepository.GetListAsync(e => e.PhoneNum == phoneNum);

            if (data.IsNullOrEmpty())
            {
                return new ApiResult("用户不存在!");
            }
            else if (data.Count>1) 
            {
                throw new ApplicationException($"存在多条手机号{phoneNum}");
            }
            else
            {
                var dto = mapper.Map<List<AdminUserDTO>>(data);
                return new ApiResult(dto);
            }
        }

        public async Task<ApiResult> HasPermissionAsync(long UserId, string permissionName)
        {
           
            if (!await AdminUserRepository.IsExistAsync(e=>e.Id==UserId)) return new ApiResult("用户不存在");
            if (AdminUserRepository.HasPermissionAsync(UserId, permissionName))
                return new ApiResult(true);
            return new ApiResult("没有权限");
        }

        public async Task<ApiResult> MarkDeleteAsync(long adminUserId)
        {
            if (await AdminUserRepository.IsExistAsync(e => e.Id == adminUserId))
            {
                var res = await AdminUserRepository.UpdateIsDeleteAsync(e => e.Id == adminUserId);
                return res <= 0 ? new ApiResult("删除失败！") : new ApiResult();
            }
             return new ApiResult("用户不存在");
           
        }

        public Task<ApiResult> RecordLoginErrorAsync(long id)
        {
            throw new NotImplementedException();
        }

        public Task<ApiResult> ResetLoginErrorAsync(long id)
        {
            throw new NotImplementedException();
        }

        public async Task<ApiResult> UpdatePswAsync(string phoneNum, string password)
        {
            var data = await AdminUserRepository.GetModelAsync(e => e.PhoneNum == phoneNum);
            if (data == null)
                return new ApiResult("用户不存在");
            var salt = CommonHelper.CreateVerifyCode(8);
            data.PasswordHash = CommonHelper.CalcMD5(password + salt);
            data.PasswordSalt = salt;
            var newdata = await AdminUserRepository.UpdateAsync(data);
            return newdata <= 0 ? new ApiResult("修改失败！") : new ApiResult();
        }

        public async Task<ApiResult> UpdateUserAsync(long id, string name, string phoneNum, string email, long? cityid)
        {
            var data = await AdminUserRepository.GetModelAsync(e =>e.Id==id);
            if (data==null)
            return new ApiResult("用户不存在");
            data.Name = name;
            data.PhoneNum = phoneNum;
            data.Email = email;
            data.CityId = cityid;
            var res = await AdminUserRepository.UpdateAsync(data);
            return res <= 0 ? new ApiResult("更新失败！") : new ApiResult();
        }
    }
}
